# !/usr/bin/env python
# coding=utf-8
# @Time    : 2018/7/16 13:07
# @Author  : 6imensiva
# @Site    : https://gitee.com/dimensiva/rpc_dao.git
# @File    : insurance_types.py
# @Software: PyCharm
# @Version: 2.7.5
from . import Session
from db.models import TInsuranceType, TInsuranceUnit, TAreaInsuranceUnit, TCity, TCommissionRate
from sqlalchemy import and_


def get_insurance_types():
	session = Session()
	return session.query(TInsuranceType).order_by(TInsuranceType.id.asc()).all()


def get_gbcode_id(city_code):
	session = Session()
	obj = session.query(TCity).filter_by(gbcode=city_code).first()
	return obj.ProvinceID, obj.CityID


def get_insurance_units(province_id, city_id, appId):
	session = Session()
	sub_qry = session.query(TAreaInsuranceUnit.insuranceUnitId).\
		filter_by(and_(insuranceUnitId=1), and_(provinceID=province_id),
	              and_(cityID=city_id), and_(app_id=appId)).subquery()
	return session.query(TInsuranceUnit).filter_by(and_(TInsuranceUnit.id.in_(sub_qry)),
	                                        and_(status=1)).all()


def get_commission_rate(appId, cityCode, insuranceCode):
	session = Session()
	rate1 = session.query(TCommissionRate.rate1).filter(and_(TCommissionRate.ins_corp_id == TInsuranceUnit.id),
	                                                    and_(TInsuranceUnit.unit_code == insuranceCode),
	                                                    and_(TCommissionRate.city_code == cityCode),
	                                                    and_(TCommissionRate.app_id == appId),
	                                                    and_(TCommissionRate.status == 1)).first()
	if not rate1:
		rate1 = '0.00'
	return rate1
